import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class HttpPage extends StatefulWidget {
  const HttpPage({super.key});

  @override
  State<HttpPage> createState() => _HttpPageState();
}

class _HttpPageState extends State<HttpPage> {

  String _data = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter App"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(onPressed: () async {

              //Get请求
              var url = Uri.http("a.itying.com","/api/productlist");
              var response = await http.get(url);

              //json字符串转Map对象
              var ret = json.decode(response.body);

              setState(() {
                _data = "Get请求结果为:${ret["result"][0]["title"]}";
              });
            }, child: const Text("Get请求")),
            ElevatedButton(onPressed: () async {
              //Post请求
              var url = Uri.https('example.com', 'whatsit/create');
              var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});

              print('Response status: ${response.statusCode}');
              print('Response body: ${response.body}');
            }, child: const Text("Post请求")),
            const Divider(),
            const Text("请求结果:"),
            Text(_data,style: const TextStyle(fontSize: 20))
          ],
        ),
      ),
    );
  }
}
